package com.shuqi.activity;

import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.LabelListAdapter;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.MyListFooter;
import com.shuqi.activity.viewport.MyListFooter.MyFooterListener;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.LabelListController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.model.BookInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.LabelListInfo;

/**
 * 标签列表Activity
 * 
 * @author zhuchen
 * 
 */
public class LabelListActivity extends ActivityBase implements OnClickListener, IEventListener,
        OnItemClickListener {
    private CommonTitle mTitle;
    private String cid = "";
    private LabelListController controller;
    private LabelListInfo labelListInfo; // 返回数据
    private List<BookInfo> list;
    private List<BookInfo> templist;
    private ListView act_label_list;
    private LabelListAdapter adapter;
    private final int init = EventTypeConstants.BASE;
    private final int init_success = init + 1;
    private final int init_error = init_success + 1;
    private final int loadmore_error = init_error + 1;
    private MyListFooter listFooter;
    private int pageIndex = 1;// 请求页
    /** 进度圈 */
    private LinearLayout layoutLoading;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case init:
                    activityLogicForward();
                    break;
                case init_success:
                    act_label_list.setVisibility(View.VISIBLE);
                    activityInitData();
                    findViewById(R.id.include_error).setVisibility(View.GONE);
                    break;
                case init_error:
                    layoutLoading.setVisibility(View.GONE);
                    act_label_list.setVisibility(View.GONE);
                    findViewById(R.id.include_error).setVisibility(View.VISIBLE);
                    break;
                case loadmore_error:
                    layoutLoading.setVisibility(View.GONE);
                    listFooter.loadingError();
                    showMsg("网络异常");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_label);
        this.controller =
                (LabelListController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_LabelList, this);
        this.controller.addEventListener(this);
        handler.sendEmptyMessage(init);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                pageIndex++;
                labelListInfo = (LabelListInfo) data;
                templist = labelListInfo.getList();
                if (list == null) {
                    list = templist;
                } else {
                    this.list.addAll(templist);
                }
                handler.sendEmptyMessage(init_success);
                break;
            default:
                if (list == null) {
                    handler.sendEmptyMessage(init_error);
                } else {
                    handler.sendEmptyMessage(loadmore_error);
                }
                break;
        }
    }

    @Override
    public void activityLogicForward() {
        this.layoutLoading = (LinearLayout) findViewById(R.id.include_loading);

        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mTitle.setTitle(getIntent().getStringExtra("keywordName"));
        cid = getIntent().getStringExtra("keywordId");

        act_label_list = (ListView) findViewById(R.id.act_label_list);

        MyFooterListener listener = new MyFooterListener() {
            @Override
            public void reload() {
                controller.handle(0, cid, pageIndex);
                listFooter.loadingStart();
            }

            @Override
            public void loadNext() {
                controller.handle(0, cid, pageIndex);
                listFooter.loadingStart();
            }

            @Override
            public boolean hasNext() {
                if (list == null) {
                    return false;
                }
                return (list.size() < totalCount) || (list != null && templist == null);
            }
        };
        listFooter = new MyListFooter(this, listener);
        act_label_list.addFooterView(listFooter);

        act_label_list.setOnItemClickListener(this);
        findViewById(R.id.retry).setOnClickListener(this);

        // 请求数据，loading页面显示
        controller.handle(0, this.cid, this.pageIndex);
        listFooter.loadingStart();
        this.layoutLoading.setVisibility(View.VISIBLE);
    }

    int totalCount;

    @Override
    public void activityInitData() {
        this.layoutLoading.setVisibility(View.GONE);
        if (adapter == null) {
            adapter = new LabelListAdapter(this, this.list);
            adapter.setDataList(this.list);
            act_label_list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        // 如果没有数据
        if (list.size() == 0) {
            ((TextView) findViewById(R.id.act_label_text_nomore)).setVisibility(View.VISIBLE);
        }
        // 如果显示完整，则改变状态
        totalCount = Integer.parseInt(labelListInfo.getTotalCount());
        listFooter.loadingSuccess();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(list==null || position>=list.size()){
            return;
        }
        BookInfo bookInfo = list.get(position);

        Log4an.d("liyizhe", "hide:" + bookInfo.getBookHideState());
        Log4an.d("liyizhe", "cover:" + bookInfo.getCoverHideState());

        if (!("N".equals(bookInfo.getBookHideState()))) {
            showMsg(getResources().getString(R.string.error_bookswitch_ishide));
            return;
        }
        if (!(1 == bookInfo.getCoverHideState())) {
            showMsg(getResources().getString(R.string.error_bookswitch_coverisclose));
            return;
        }
        BookCoverActivity.openBookCoverForAvoidCycle(this, bookInfo.getBookId());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                } else {
//                    layoutLoading.setVisibility(View.VISIBLE);
//                    controller.handle(0, cid, pageIndex);
//                }
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        layoutLoading.setVisibility(View.VISIBLE);
                        controller.handle(0, cid, pageIndex);

                    }
                });
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
